﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class UserRolesByUsers : ClassManager.SessionManagerPage
    {

        private void GetAllUsersByCompany(int companyId)
        {
            try
            {
                UsersGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.UsersProvider.GetByCompanyID(companyId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.UsersColumn.Name.ToString();
                expression.SetSortOrder("Ascending");
                this.UsersGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                expression = new GridSortExpression();
                expression.FieldName = "Name";
                expression.SetSortOrder("Ascending");
                this.UserRolesGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }


        private void ResizeGrid()
        {
            decimal Height = Convert.ToDecimal(HiddenFieldHeight.Value) / 2;

            UserRolesGrid.Height = Unit.Parse(Convert.ToString(Height));
            UsersGrid.Height = Unit.Parse(Convert.ToString(Height));
        }

        protected void uscRolesSearch_OnCancelEvent()
        {
            ResizeGrid();
        }

        protected void uscRolesSearch_OnAcceptEvent(List<GridDataItem> rows)
        {
            string Username = getUsersGridValueSelected();

            if (Username == "" && rows.Count > 0)
            {
                showWarningMessage("Debe seleccionar un usuario para asociar las pantallas.");
            }
            else
            {

                foreach (GridDataItem row in rows)
                {

                    GPSTrackingDBV2.Entities.UserRolesByUsers UserRolesByUsersEntity = new GPSTrackingDBV2.Entities.UserRolesByUsers();
                    UserRolesByUsersEntity.Dispose();
                    UserRolesByUsersEntity.Username = Username;
                    UserRolesByUsersEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;
                    UserRolesByUsersEntity.UserRolesId = int.Parse(row.Cells[3].Text);

                    GPSTrackingDBV2.Data.DataRepository.UserRolesByUsersProvider.Insert(UserRolesByUsersEntity);
                }
                GetUserRolesByUsername(Username);
                UserRolesGrid.DataBind();
            }
            ResizeGrid();
        }

        protected void UsersGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                GetAllUsersByCompany(getSessionManager().CompanyIDSelectedComboBox);
            }
            catch (Exception ex)
            {
                showErrorMessage("No se pudo cargar la información de los usuarios");
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
            }
        }

        protected void UserRolesGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Data.DataRepository.UserRolesByUsersProvider.Delete(int.Parse(Entity["UserRolesId"].ToString()), getUsersGridValueSelected(), getSessionManager().CompanyIDSelectedComboBox);

            }
            catch (Exception ex)
            {
                showErrorMessage("No se pudo quitar el rol del usuario seleccionado.");
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
            }
        }

        protected void UsersGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            string username = getUsersGridValueSelected();
            setSessionManager(username);           

            GetUserRolesByUsername(username);
            UserRolesGrid.DataBind();
            ResizeGrid();
        }

        protected void setSessionManager(string value)
        {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
            objSessionManager.UsernameForRole = value;
            HttpContext.Current.Session["SessionManager"] = objSessionManager;
        }

        protected string getUsersGridValueSelected()
        {

            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in UsersGrid.SelectedItems)
                {
                    return selectedItem["Username"].Text;
                }
            }
            catch {}
            return "";
        }

        protected void UserRolesGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            GetUserRolesByUsername(getUsersGridValueSelected());
            ResizeGrid();
        }

        protected void GetUserRolesByUsername(string username){
            UserRolesGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.UserRolesProvider.GetAllByUsernameAndCompanyID(getSessionManager().CompanyIDSelectedComboBox, username);
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Asignación de Roles...');", true);
        }

        public void showInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Asignación de Roles...');", true);
        }

        public void showWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Warning", "objWindowsMessageManager.show_Warning('" + msg + "','Asignación de Roles...');", true);
        }

        protected void lbClearUsersFilters_Click(object sender, EventArgs e)
        {
            UsersGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in UsersGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            UsersGrid.MasterTableView.Rebind();
            clearUserRolesGrid();
            ResizeGrid();
        }

        protected void lbClearUserRolesFilters_Click(object sender, EventArgs e)
        {
            UserRolesGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in UserRolesGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            UserRolesGrid.MasterTableView.Rebind();
            ResizeGrid();
        }

        private void clearUserRolesGrid()
        {
            UserRolesGrid.DataSource = new string[] { };
            UserRolesGrid.DataBind();
            ResizeGrid();
        }

        protected void UsersGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.SortCommandName || e.CommandName == RadGrid.FilterCommandName)
            {
                clearUserRolesGrid();
            }
        }
    }
}